<template>
  <div class="app-container">
    <!-- 添加按钮,搜索表单-->
    <div>
      <!-- 添加按钮-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['sell:salesOrder:add']"
        >新增销售单
        </el-button>
      </el-col>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="daterangeOrderTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择订单状态"
            clearable
            @keyup.enter.native="handleQuery"
            @change="getUniqueList">
            <el-option v-for="dict in dict.type.erp_sales_status"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 打印按钮-->
      <div style="text-align: right;">
        <el-form>
          <el-form-item>
            <el-button
              type="info"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['sell:salesOrder:export']"
            >导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 销售订单列表 -->
    <el-table v-loading="loading" :data="salesOrderList">
      <el-table-column label="订单ID" align="center" prop="orderId" width="100"/>
      <el-table-column label="商品信息" align="left" prop="erpSalProductsVOList" width="210">
        <template slot-scope="scope">
          <div v-for="item in scope.row.erpSalProductsVOList" :key="item.productId">
            {{ item.productName }} - ￥{{ item.price }} * {{ item.count }}{{ item.unit }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="left" prop="erpCustomer" width="220">
        <template slot-scope="scope">
          名称: {{ scope.row.erpCustomer.custName }} <br>
          {{ scope.row.erpCustomer.contact }}: {{ scope.row.erpCustomer.phone }} <br>
          地址: {{ scope.row.erpCustomer.addr }}
        </template>
      </el-table-column>
      <el-table-column label="总价格(￥)" align="center" prop="totalAmt"/>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_sales_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['sell:salesOrder:edit']"
          >提交
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sell:salesOrder:remove']"
          >取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit="20"
      :page-sizes="[999999999,88888888,666666]"
      layout="total, prev, pager, next, sizes"
      @pagination="getList"
    />

    <!-- echarts图表 -->
    <div id="main" style="width: 100%; height: 400px;">
      <!-- 弄一个饼状图,显示订单状态分布 -->
      <!-- data中定义一个订单状态分布的数组：第一个是交易中,第二个是已完成,第三个是已取消的个数。如【2,3,1】 -->
      <!-- 新建方法和api获取数据并存放到数组里面，每次进行增删改后都更新数组 -->
      <!-- echarts渲染饼状图 -->

    </div>

    <!-- 添加对话框 -->
    <el-dialog title="添加销售订单" :visible.sync="open" width="750px" append-to-body>
      <!-- 用户 -->
      <el-form ref="form" :model="form" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="custName">
              <el-select v-model="form.custId" placeholder="请选择客户名称" @change="handleCustomerChange" size="small" style="width: 100%">
                <el-option v-for="item in customerList"
                           :key="item.custId" :label="item.custName" :value="item.custId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" readonly size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" readonly size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="addr">
              <el-input v-model="form.addr" readonly size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 商品 -->
      <div>
        <!-- 添加按钮 -->
        <div style="margin-bottom: 15px;">
          <el-button type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
        </div>
        <!-- 商品列表 -->
        <div style="margin-bottom: 15px;">
          <el-table :data="selectedProducts" border height="300px" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" width="150"></el-table-column>
            <el-table-column prop="unit" label="单位" width="80"></el-table-column>
            <el-table-column prop="price" label="单价(￥)" width="100"></el-table-column>
            <el-table-column label="数量" width="160">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.count"
                  :min="1"
                  :max="9999"
                  @change="calculateTotal"
                  size="small">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="小计(￥)" width="100">
              <template slot-scope="scope">
                {{ (scope.row.price * scope.row.count).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="removeProduct(scope.$index)"
                  size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 总价格 -->
        <div style="text-align: right;">
          <span style="font-size: 16px; font-weight: bold;">
            总价格: ￥{{ totalPrice.toFixed(2) }}
          </span>
        </div>
      </div>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog title="选择商品" :visible.sync="productDialogVisible" width="880px" append-to-body>
      <!-- 商品类型筛选下拉框 -->
      <div style="margin-bottom: 15px;">
        <el-form :inline="true" size="small">
          <el-form-item label="商品类型:">
            <el-select
              v-model="selectedProductType"
              placeholder="请选择商品类型"
              clearable
              @change="filterProductsByType"
              style="width: 200px;">
              <el-option
                v-for="type in productTypes"
                :key="type"
                :label="type"
                :value="type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="resetProductFilter">重置筛选</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="filteredProductList"
        border
        @selection-change="handleProductSelectionChange"
        height="400px"
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="productImage" label="商品图片" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.productImage" fit="fill" :preview-src-list="[scope.row.productImage]" />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="150"></el-table-column>
        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
        <el-table-column prop="price" label="单价(￥)" width="100"></el-table-column>
        <el-table-column prop="productDetail" label="商品描述"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddProducts">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listSalesOrder, delSalesOrder, addSalesOrder, updateSalesOrder, getOrderStatusStatistics} from "@/api/sell/salesOrder"
import { checkPermi } from "@/utils/permission";
import {listCustomer} from "@/api/sell/customer"
import {listProducts} from "@/api/product/listProducts"

export default {
  name: "SalesOrder",
  dicts: ['erp_sales_status'],
  data() {
    return {
      // ================ 主体部分 ======================
      // 遮罩层
      loading: true,
      // 销售订单表格数据
      salesOrderList: [],

      // 总条数
      total: 0,
      // 查询参数
      daterangeOrderTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 999999999,
        orderId: null,
        orderTime: null,
        status: null
      },
      // ================ 弹出层部分 ======================
      // 是否显示弹出层
      open: false,
      // 添加对话框的表单参数
      form: {},
      // 客户名称列表
      customerList: [],
      // 商品相关数据
      productDialogVisible: false, // 商品选择对话框显示状态
      productList: [], // 所有商品列表
      productTypes: [], // 商品类型列表
      filteredProductList: [], // 筛选后的商品列表
      selectedProductType: '', // 选中的商品类型
      selectedProducts: [], // 已选择的商品列表
      selectedProductIds: [], // 已选择的商品ID列表
      totalPrice: 0, // 总价格
      // ================ 图表相关 ======================
      orderStatusData: [0, 0, 0], // 订单状态分布数组：[交易中, 已完成, 已取消]
      chartInstance: null // echarts实例
    }
  },
  created() {
    this.getList()
    this.getOrderStatusStatistics()
  },
  beforeDestroy() {
    // 销毁echarts实例
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
  },
  methods: {
    // ============== 销售订单_查询,修改 =======================
    /** 查询销售订单列表 */
    getList() {
      this.loading = true
      if (null != this.daterangeOrderTime && '' != this.daterangeOrderTime) {
        this.queryParams.params["beginOrderTime"] = this.daterangeOrderTime[0]
        this.queryParams.params["endOrderTime"] = this.daterangeOrderTime[1]
      }
      listSalesOrder(this.queryParams).then(response => {
        // 展示表单修改->修改salesOrderList
        this.salesOrderList = response.rows
        this.total=response.total
        this.loading = false
      })
    },
    /** 订单状态下拉列表-选择查询 */
    getUniqueList(value) {
      if (!checkPermi(['sell:salesOrder:query'])) {
        this.$message.error("没有权限执行该操作");
        return;
      }
      this.queryParams.pageNum = 1
      this.queryParams.status = value
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (!checkPermi(['sell:salesOrder:query'])) {
        this.$message.error("没有权限执行该操作");
        return;
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 编辑按钮操作[修改销售订单状态-到已完成] */
    handleEdit(row) {
      if (row.status != 1) {
        // this.$modal.msgError("只有待处理订单才能提交")
        return
      }
      updateSalesOrder(row.orderId).then(response => {
        this.$modal.msgSuccess("提交成功")
        this.getList()
        this.getOrderStatusStatistics() // 更新图表数据
      })
    },
    /** 删除按钮操作[取消销售订单-到已取消] */
    handleDelete(row) {
      if (row.status != 1) {
        // this.$modal.msgError("只有待处理订单才能取消")
        return
      }
      this.$modal.confirm('是否确认取消销售订单编号为"' + row.orderId + '"的数据项？').then(function () {
        return delSalesOrder(row.orderId)
      }).then(() => {
        this.getList()
        this.getOrderStatusStatistics() // 更新图表数据
        this.$modal.msgSuccess("取消成功")
      }).catch(() => {
      })
    },
    // =====================================

    // ============== 销售订单_新增 =======================
    /** 新增订单按钮操作 */
    handleAdd() {
      // 添加权限判断
      if (!checkPermi(['sell:salesOrder:add','sell:customer:list','erp:product:list'])) {
        this.$message.error("没有权限执行该操作");
        return;
      }
      this.reset()
      // 查询所有顾客并且存储到customerList
      listCustomer().then(response => {
        this.customerList = response.rows
      })
      this.open = true
      this.title = "添加销售订单"
    },
    /** 客户名称下拉列表-选择回显 */
    handleCustomerChange(custId) {
      const customer = this.customerList.find(item => item.custId === custId);
      if (customer) {
        this.form.contact = customer.contact;
        this.form.phone = customer.phone;
        this.form.addr = customer.addr;
      } else {
        this.form.contact = '';
        this.form.phone = '';
        this.form.addr = '';
      }
    },
    // dialog添加表单重置
    reset() {
      this.form = {}
      this.resetForm("form")
      // 重置商品相关数据
      this.selectedProducts = []
      this.totalPrice = 0
      this.selectedProductIds = []
      this.productList = []
      this.filteredProductList = []
      this.productTypes = []
      this.selectedProductType = ''
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false
      this.reset()
    },

    /** 提交按钮_只做添加 */
    submitForm() {
      // 检查是否选择了客户
      if (!this.form.custId) {
        this.$modal.msgWarning('请选择客户')
        return
      }
      // 检查是否选择了商品
      if (this.selectedProducts.length === 0) {
        this.$modal.msgWarning('请至少添加一个商品')
        return
      }
      // 构建提交数据
      const submitData = {
        // 客户id
        custId: this.form.custId,
        // 商品id和对应数量
        productsList: this.selectedProducts.map(product => ({
          productId: product.productId,
          count: product.count
        })),
        totalAmt: this.totalPrice
      }
      // 提交新增订单
      addSalesOrder(submitData).then(response => {
        this.$modal.msgSuccess("新增成功")
        this.open = false
        this.getList()
        this.getOrderStatusStatistics() // 更新图表数据
      })
    },
    /** 添加商品按钮操作 */
    handleAddProduct() {
      // 查询所有商品并且存储到productList_初始化
      listProducts({pageSize : 999999999}).then(response => {
        this.productList = response.rows
        // 提取商品类型列表（去重）
        this.productTypes = [...new Set(this.productList.map(product => product.productType).filter(type => type))]
        // 初始化筛选后的商品列表
        this.filteredProductList = [...this.productList]
        // 重置筛选条件
        this.selectedProductType = ''
      })
      this.productDialogVisible = true
    },
    /** 根据商品类型筛选商品 */
    filterProductsByType() {
      if (this.selectedProductType) {
        this.filteredProductList = this.productList.filter(product =>
          product.productType === this.selectedProductType
        )
      } else {
        this.filteredProductList = [...this.productList]
      }
    },
    /** 重置商品筛选 */
    resetProductFilter() {
      this.selectedProductType = ''
      this.filteredProductList = [...this.productList]
    },
    /** 商品选择变化处理 */
    handleProductSelectionChange(selection) {
      this.selectedProductIds = selection.map(item => item.productId)
    },
    /** 确认添加商品 */
    confirmAddProducts() {
      if (this.selectedProductIds.length === 0) {
        this.$modal.msgWarning('请选择要添加的商品')
        return
      }

      // 获取选中的商品（从筛选后的列表中获取）
      const selectedProducts = this.filteredProductList.filter(item =>
        this.selectedProductIds.includes(item.productId)
      )

      // 检查是否已存在相同商品
      selectedProducts.forEach(product => {
        const existingIndex = this.selectedProducts.findIndex(item => item.productId === product.productId)
        if (existingIndex === -1) {
          // 添加新商品，默认数量为1
          this.selectedProducts.push({
            ...product,
            count: 1
          })
        } else {
          // 如果商品已存在，增加数量
          this.selectedProducts[existingIndex].count += 1
        }
      })

      // 重新计算总价格
      this.calculateTotal()

      // 关闭对话框
      this.productDialogVisible = false
      this.selectedProductIds = []
    },
    /** 删除商品 */
    removeProduct(index) {
      this.selectedProducts.splice(index, 1)
      this.calculateTotal()
    },
    /** 计算总价格 */
    calculateTotal() {
      this.totalPrice = this.selectedProducts.reduce((total, product) => {
        return total + (product.price * product.count)
      }, 0)
    },
    // =====================================

    // ============== 销售订单_导出 =======================
    /** 导出按钮操作 */
    handleExport() {
      this.download('sell/salesOrder/export', {
        ...this.queryParams
      }, `salesOrder_${new Date().getTime()}.xlsx`)
    },

    // ============== 图表相关方法 =======================
    /** 获取订单状态统计 */
    getOrderStatusStatistics() {
      getOrderStatusStatistics().then(response => {
        // 重置数组
        this.orderStatusData = [0, 0, 0]
        // 根据返回的数据更新数组
        response.data.forEach(item => {
          const status = parseInt(item.status)
          const count = parseInt(item.count)
          if (status >= 1 && status <= 3) {
            this.orderStatusData[status - 1] = count
          }
        })
        // 渲染图表
        this.$nextTick(() => {
          this.renderChart()
        })
      }).catch(error => {
        console.error('获取订单状态统计失败:', error)
      })
    },

    /** 渲染echarts饼状图 */
    renderChart() {
      // 确保DOM元素存在
      const chartDom = document.getElementById('main')
      if (!chartDom) {
        console.error('图表容器不存在')
        return
      }

      // 如果已存在实例，先销毁
      if (this.chartInstance) {
        this.chartInstance.dispose()
      }

      // 创建echarts实例
      this.chartInstance = this.$echarts.init(chartDom)

      // 配置选项
      const option = {
        title: {
          text: '销售订单状态分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['交易中', '已完成', '已取消']
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: '50%',
            center: ['60%', '50%'],
            data: [
              { value: this.orderStatusData[0], name: '交易中', itemStyle: { color: '#409EFF' } },
              { value: this.orderStatusData[1], name: '已完成', itemStyle: { color: '#67C23A' } },
              { value: this.orderStatusData[2], name: '已取消', itemStyle: { color: '#F56C6C' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b}: {c}'
            }
          }
        ]
      }

      // 设置配置项并渲染
      this.chartInstance.setOption(option)

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
      })
    }
  }
}
</script>
